package com.feng.common.utils;


import com.feng.common.enums.CommonErrorCode;
import com.feng.common.model.LoginUser;

/**
 * 用户信息上下文
 *
 * @author Jack.Cheng
 * @date 2022/12/18 下午8:46
 */
public class SessionUserContextHolder {

    private static final ThreadLocal<LoginUser> USER_CONTEXT = new ThreadLocal<>();

    public static void set(LoginUser loginUser) {
        USER_CONTEXT.set(loginUser);
    }

    public static LoginUser get() {
        LoginUser loginUser = USER_CONTEXT.get();
        AssertUtils.isNotNull(loginUser, CommonErrorCode.UNAUTHORIZED);
        return loginUser;
    }

    public static LoginUser getOrDefault(LoginUser defaultUser) {
        LoginUser loginUser = USER_CONTEXT.get();
        if (null == loginUser) {
            return defaultUser;
        }
        return loginUser;
    }

    public static void clear() {
        USER_CONTEXT.remove();
    }
}
